angular.module('imsApp').controller('promotionDetailController', ['$scope', '$rootScope', '$state', 'PromotionGroupManager', '$stateParams','$filter','TagsManager','$uibModal',
    function ($scope, $rootScope, $state, PromotionGroupManager, $stateParams,$filter,TagsManager,$uibModal) {
    $scope.campaignId = $stateParams.campaignsId;
        console.log($scope.campaignId,"$scope.campaignId$scope.campaignId$scope.campaignId")
    $scope.groupId = $stateParams.groupId;
    $scope.advertiserId = $stateParams.advertiserId;
    $scope.adStyle = $stateParams.adStyle;//新建创意用

    //页面初始化用数据
    $scope.initData = {
        "codeTable": $scope.table,
        "initCode" : {
            "targetMediaType": ["38","39","40","41"],
            "targetPlatform": ["185","186","187","188","189","190","191","192","193","194","195","196","197","198","199","200","201","202","203","204","205","206","207","208","209","210","211","212","213","214"],
            "targetOS": ["150","151","152","153"],
            "targetScreen": ["220","221","222","223","224","225","226","227","228","229","230","231","232","233","234","235","236","237","238","239","240","241","242","243","244","245","246"],
            "targetNet": ["154","155","156","157","158","159"],
            "targetOperator": ["160","161","162","163"],
            "targetRegional": [
                ["999999",[
                    ["110000"],["310000"],["120000"],["500000"],["130000",["130100","130600","130200","130300"]],["140000",["140100"]],["210000",["210100","210200"]],["220000",["220100","220200"]],["230000",["230100"]],["320000",["320100","320200","320500"]],["330000",["330100","330200"]],["340000",["340100"]],["350000",["350100"]],["360000",["360100"]],["370000",["370100","370200"]],["410000",["410100"]],["420000",["420100"]],["430000",["430100"]],["440000",["440100","440300"]],["460000",["460100"]],["510000",["510100"]],["520000",["520100"]],["530000",["530100"]],["610000",["610100"]],["620000",["620100"]],["630000",["630100"]],["150000",["150100"]],["450000",["450100"]],["540000",["540100"]],["640000",["640100"]],["650000",["650100"]],["810100"],["820100"],["710000",["710100"]]
                ]]
            ],
            "targetInternet": ["170","171","172","173"],
            "targetTags":[]
        }
    };

    $scope.isLoadOne = false;
    //ctrlData初始化方法
    var ctrlDataInit = function(data) {
        //判断是否有数据回来，有的话就变成数组，没有的话就初始化数据。
        if(angular.isDefined(data)) {
            $scope.formData = data;
            //To be Array
            $scope.formData.targetMediaType = data.targetApp == null||data.targetApp=="" ? data.targetMediaType.length>0 ? $filter("toArray")(data.targetMediaType):["38","39","40","41"]:[];
            $scope.formData.targetPlatform = $filter("toArray")(data.targetPlatform);
            $scope.formData.targetOS = $filter("toArray")(data.targetOS);
            $scope.formData.targetScreen = $filter("toArray")(data.targetScreen);
            $scope.formData.targetNet = $filter("toArray")(data.targetNet);
            $scope.formData.targetOperator = $filter("toArray")(data.targetOperator);
            $scope.formData.targetInternet = $filter("toArray")(data.targetInternet);
            $scope.formData.targetRegional = $filter("toArray")(data.targetRegional);
            $scope.formData.targetTags = $filter("toArray")(data.targetTags);
        } else {
            formDataInit();
        }
        //判断是否是编辑
        if($scope.planEdit && $scope.isLoadOne == false) {
            $scope.ctrlData = {
                "targetMediaType": 1,"targetPlatform": 1, "targetOS": 1,"targetScreen": 1,
                "targetNet": 1,"targetOperator": 1,"targetInternet": 1, "targetRegional": 1,
                "targetRegionalFormart":{
                    "countryItem": [],
                    "provinceItem": [],
                    "cityItem": []
                },
                "targetTags":1,
                "targetTagsFormart":{//详情框用
                    "parentItem": [],
                    "childItem": []
                },
                "newTag":"",//用于存添加新内容兴趣标签时的值
            };
        } else {
            $scope.ctrlData = {
                "targetMediaType": $scope.formData.targetApp != null ? 2 : 1,
                "targetPlatform": $scope.formData.targetPlatform != null ? $scope.formData.targetPlatform.length ? 2 : 1 : 1,
                "targetOS": $scope.formData.targetOS != null ? $scope.formData.targetOS.length ? 2 : 1 : 1,
                "targetScreen": $scope.formData.targetScreen != null ? $scope.formData.targetScreen.length ? 2 : 1 : 1,
                "targetNet": $scope.formData.targetNet != null ? $scope.formData.targetNet.length ? 2 : 1:1,
                "targetOperator": $scope.formData.targetOperator != null ? $scope.formData.targetOperator.length ? 2 : 1 : 1,
                "targetInternet": $scope.formData.targetInternet != null ? $scope.formData.targetInternet.length ? 2 : 1 : 1,
                "targetRegional": $scope.formData.targetRegional != null ? $scope.formData.targetRegional.length ? 2 : 1 : 1,
                "targetRegionalFormart": regionInit(),
                "targetTags":$scope.formData.targetTags != null ? $scope.formData.targetTags.length ? 2 : 1 : 1,
            };
            $scope.isLoadOne=false;
        }
    };

    //formData初始化方法
    var formDataInit = function() {
        $scope.formData = {
            "targetSim": 180,"targetMediaType": [],"targetPlatform": [],"targetOS": [], "targetScreen": [],
            "targetNet": [],"targetOperator": [], "targetInternet": [], "targetRegional": [],"targetTags": [],
        };
        $scope.formData.advertiserId = $stateParams.advertiserId;
        $scope.planEdit = true;
    };

    /**
     * 1.省市地域选择数据 初始化
     */
    var regionInit = function(){
        return PromotionGroupManager.initRegion($scope,$stateParams);
    };

    //回写内容兴趣标签
    $scope.tagSelected = [];//存放已选结果,json数组
    $scope.backTag = function(result){
        PromotionGroupManager.backTag($scope,result);
    };

    //加载内容标签成功
    var copy = [];
    $scope.selectOne = false;
    var getTagsSuccess = function(result){
        $scope.tagsResult = result;
        copy=angular.copy(result);
        if($stateParams.groupId){
            $scope.backTag(result.splice(0,1));//回写内容标签
            setTimeout(function(){
                $scope.$apply($scope.backTag(copy));
            },1000);
        }

        if($scope.selectOne && $scope.formData.targetTags.length>0){
            setTimeout(function(){
                $scope.$apply($scope.backTag(copy));
            },1000);
            $scope.selectOne = false;
        }
    };

        //加载内容标签
    $scope.loadTags = function(){
        TagsManager.tagList().then(function (result) {
            getTagsSuccess(result.data.pageList);
        })
        // PromotionGroupManager.getGroupData( {},"ims/tagList.do",getTagsSuccess);
    };

    /** 点自定义时得到标签 */
    $scope.getTagData = function(){
        if(!$scope.tagsResult){
            $scope.loadTags();
        }
    };
        $scope.getTagData();


        //回写全选
    var backSelectAll = function(){
        //要回写的字段
        var array = ["targetPlatform","targetOS","targetScreen","targetNet","targetOperator","targetInternet"];
        for(var i=0; i<array.length; i++){
            $scope.allName.push(array[i]);
            $scope.halfData[array[i]] = $scope.formData[array[i]].length==0 ? false : ($scope.initData.initCode[array[i]].length == $scope.formData[array[i]].length) ? false : true;
        }
    };

    //获取详情成功回调方法
    var getDataSuccess = function(result) {
        if(result.c == 's') {
            $scope.formData = result.adGroupVO;
            ctrlDataInit(result.adGroupVO);
            $scope.title= result.title;
            backSelectAll();//回写全选
        } else {
            alert(result.i);
        }
    };
    //判断是否进入新建
    if(!$stateParams.groupId) {//添加
        ctrlDataInit();
    } else {//详情
        PromotionGroupManager.promotionGroupDetail($scope.groupId).then(function (result) {
            console.log(result)
            getDataSuccess(result.data);
        })
        $scope.loadTags();//加载内容标签列表
    }

    //定义全选容器
    $scope.checkBoxAllData={"targetPlatform":[] ,'targetOS':[] ,'targetScreen':[] ,"targetNet":[] ,"targetOperator":[]};
    //存全选结果
    $scope.allName=[];
    //checkbox全选框初始化
    $scope.checboxAll = function(target,val){
        if(angular.isUndefined($scope.checkBoxAllData)) {
            return false;
        } else {
            return $scope.allName.indexOf(target.toString())>=0;
        }
    };

    //全选
    $scope.selectAll = function($event,target) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        var allDex = $scope.allName.indexOf(target.toString());
        var str = target.toString();
        if(action == 'add'){
            $scope.halfData[target] = false;
            $scope.formData[target.toString()] = [];
            for(var i=0;i<$scope.initData.initCode[str].length;i++){
                $scope.formData[target.toString()].push($scope.initData.initCode[str][i]);
            }
            if(allDex == -1){
                $scope.allName.push(str);
            };
        }else if(action == 'remove'){
            $scope.formData[str] = [];
            if(allDex != -1){
                $scope.allName.splice(allDex,1);
            };
        };
    };

    //定义部分选中
    $scope.halfData={};
    //checkbox数据添加删除方法
    var updateSelected = function(action,target,id){
        if(action == 'add' && $scope.formData[target].indexOf(id) == -1){
            $scope.formData[target].push(id);
            if($scope.formData[target].length == $scope.initData.initCode[target].length){
                var str = target.toString();
                if($scope.allName.indexOf(str) == -1){
                    $scope.allName.push(str);
                    $scope.halfData[target] = false;
                }
            }else{
                $scope.halfData[target] = true;
            }
        }
        if(action == 'remove' && $scope.formData[target].indexOf(id)!=-1){
            var idx = $scope.formData[target].indexOf(id);
            $scope.formData[target].splice(idx,1);
            var allDex = $scope.allName.indexOf(target.toString());
            //全选时remove一个
            if(allDex != -1){
                $scope.allName.splice(allDex,1);
                $scope.halfData[target] = true;
            }else{
                //都没选中了
                if($scope.formData[target].length == 0){
                    $scope.halfData[target] = false;
                }else{
                    $scope.halfData[target] = true;
                }
            }
        };
    };

    /** 其余checkbox数据添加删除方法 */
    $scope.updateSelection = function($event,target,id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        updateSelected(action,target,id);
    };


    /** 省市地域选择 */
    //存省市地域部分选中
    $scope.halfCityData = {};
    /* 需求：如果中国选中，只后台只传中国的编号；如果某省全选，其他不选中，则只传该省编号；如果只选中某市，则只传该市的编号。
     * 如果所有国家都选中，则传1000*/
    $scope.updateSelectionNest = function($event,target,id) {
        PromotionGroupManager.checkRegion($scope,$stateParams,$event,target,id,this);
    };

    /** 内容兴趣选择 */
    //定义内容兴趣部分选中
    $scope.halfTagData = {};
    //父级内容兴趣选择
    $scope.targetTag=[];//targetTag与name值一致  ，用于存前端需要的数据的数组。$scope.formData.targetTags是存后台需要的数据的数组
    $scope.updateSelectionParentTags = function($event,target,id) {
        PromotionGroupManager.checkParent($scope,$event,target,id,this);
    };
    //子级内容兴趣选择
    $scope.updateSelectionChildTags = function($event,target,id){
        PromotionGroupManager.checkChild($scope,$event,target,id,this);
    };

    /** checkbox选择初始化 */
    $scope.isSelected = function(target, id){
        if(angular.isUndefined($scope.formData)) {
            return false;
        } else {
            return $scope.formData[target].indexOf(angular.isString(id) ? id : id.toString())>=0;
        }
    };

    /** 内容兴趣checkbox选择初始化 */
    $scope.isTagSelected = function(id){
        return $scope.targetTag.indexOf(id)>=0;
    };

    /** 编辑内容兴趣 */
    $scope.editTags = function(){
        $scope.editTag = $scope.editTag==true?false:true;

    };

    /** 添加标签获得焦点时清空 */
    $scope.addTagFocus = function(){
        $scope.ctrlData.newTag="";
    };

    /** 添加内容标签 */
    //添加内容标签成功
    var addTagSuccess = function(result){
        console.log(result);
        if(result.c=="s"){
            var c={};
            c.tagId = result.i;
            c.tagName = $scope.ctrlData.newTag;
            parentItem.list.push(c);
            $scope.ctrlData.newTag="";
        }else{
            alert(result.i);
        }
    };

    var parentItem = new Object();
    //添加
    $scope.addTag = function(nodeId){
        parentItem = this.parentItem;
        var param = {
            "nodeId":nodeId,
            "tagName":$scope.ctrlData.newTag
        };
        if($scope.ctrlData.newTag != null && $scope.ctrlData.newTag != ""){
            TagsManager.tagAdd(param).then(function (result) {
                addTagSuccess(result.data);
            })
        }

    };

    /** 删除标签 */
    //删除内容标签成功
    var delTagSuccess = function(result){
        if(result.c=="s"){
            //删除标签
            var childList = parentItem.list;
            for(var i=0;i<childList.length;i++){
                if(childList[i].tagId == childItem.tagId){
                    childList.splice(i,1);
                    break;
                }
            }
            //若已选框里有将要删除的，则删除
            for(var i=0;i<$scope.tagSelected.length;i++){
                if($scope.tagSelected[i].tagId == parentItem.tagId){
                    var list = $scope.tagSelected[i].list;
                    for(var j=0;j<list.length;j++){
                        if(list[j].tagId == childItem.tagId){
                            $scope.tagSelected[i].list.splice(j,1);
                            if($scope.tagSelected[i].list.length == 0){
                                $scope.tagSelected.splice(i,1);
                            }
                            break;
                        }
                    }
                    break;
                }
            }
        }else{
            alert(result.i);
        } ;
    };

    //删除内容标签
    var childItem = new Object();
    var parentItem = new Object();
    $scope.deleteTag = function(tagId){
        childItem = this.childItem;
        parentItem = this.parentItem;
        TagsManager.tagDelete(tagId).then(function (result) {
            delTagSuccess(result.data);
        })
    };

    /** 选择 */
    //加载单条推广组成功
    var loadSuccess = function(result) {
        if(result.data.c=="s"){
            $scope.oldName = result.data.adGroupVO.groupName;
            $scope.formData = result.data.adGroupVO;
            //修改时有groupId时所有选项不可修改，而在添加里加载一条时也有groupId，但此时是可修改的，需要将其设为0,即false
            $scope.formData.groupId=0;
            $scope.isLoadOne = true;
            $scope.selectOne = true;//用于在加载标签完成后决定是否回写
            ctrlDataInit(result.data.adGroupVO);
            $scope.loadTags();//加载内容标签列表
            backSelectAll();//回写全选
        }else{
            alert(result.data.i);
        };
    };

    //model参数配置
    $scope.modelAdvertiserParam = {
        title: "推广组选择",
        choose: function(selectedItem) {
            PromotionGroupManager.promotionGroupDetail(selectedItem.groupId).then(function (result) {
                console.log(result)
                loadSuccess(result);
            })


        },
    };
    //地域选择打开
    $scope.open = function(item) {  this[item].active = !this[item].active; };

    //model 点击打开。param：title文字、body数据、选择触发回调方法，size：model大小（big、small，默认中等大小）
    $scope.modelOpen = function (param, elm, size) {
        var modalInstance = $uibModal.open({
            templateUrl: 'myModalContent.html',
            controller: 'groupsModalController',
            size: 'normal',
            resolve: {
                param: param
            }
        });
        modalInstance.result.then(param.choose);//模态窗口打开之后执行的函数:选择
    };

    /**  提交  */
    var submitSuccess = function(result) {
        $state.go("campaigns.promotionGroup",{groupId:$scope.groupId,advertiserId:$scope.advertiserId},{reload:true});
    };
    var submitError = function() { formDataInit();};
    $scope.submits = function() {
        var tmpToSave={}
        $scope.formData.campaignId = $scope.campaignId;
        if($scope.checkGroupName()){
            for(var i in $scope.formData){
                if($scope.formData[i] instanceof Array ){
                    tmpToSave[i]=$scope.formData[i].join(",");
                }else{
                    tmpToSave[i]=$scope.formData[i];
                }
            }

            if(!$stateParams.groupId ){
                PromotionGroupManager.promotionGroupAdd($scope.campaignId,tmpToSave).then(function (result) {
                     if(result.data.c=='s'){
                         submitSuccess()
                     }else{
                         submitError()
                     }
                })
            }else {
                PromotionGroupManager.promotionGroupEdit($stateParams.groupId,tmpToSave).then(function (result) {
                    if(result.data.c=='s'){
                        submitSuccess()
                    }else{
                        submitError()
                    }

                })
            }

         //   var url = $stateParams.groupId ? "ims/updateGroup.do" : "ims/groupAdd.do";
           // pgMaintenanceService.postAddGroup($scope.formData, url,submitSuccess, submitError,$scope.allName);
        }
    };

    //修 改
    $scope.edit = function() {
        $scope.planEdit = true;
        var copyTwo=angular.copy(copy);
        $scope.tagsResult = copy.splice(0,1);
        setTimeout(function(){
            $scope.$apply($scope.tagsResult = copyTwo);
        },700);
    };

    $scope.cancel = function() {
        if(!$stateParams.groupId) {
            $state.go("campaigns.promotionGroup",{campaignId:$scope.campaignId},{reload:true});
        } else {
            if($scope.planEdit) {
                $state.reload();
            } else {
                $state.go("campaigns.promotionGroup",{campaignId:$scope.campaignId},{reload:true});
            }
        }
    };

    /** 校验 */
    //校验数据状态：1，r，e
    $scope.checkData = {"groupName": '1', };
    //提示语信息
    $scope.hintData = {"groupName":"", };
    //校验推广组名称
    $scope.checkGroupName = function(){
        var name = $scope.formData.groupName;
        if(name){
            $scope.checkData.groupName="r";
            return true;
        }else{
            $scope.checkData.groupName="e";
            $scope.hintData.groupName = "不能为空";
            return false;
        }

    };


}])

